﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using TheNorthStar.Api.Requests;
using TheNorthStar.Domain;

using TheNorthStar.Web.Application.Repository;

namespace TheNorthStar.Web.Application.Services
{
    public class BookingService : IBookingService
    {

        Repository.NorthStarDbEntities repos = new NorthStarDbEntities();
        //stub method for the time being, real implementation to come later
        public IList<Booking> GetAll()
        {

            
            return repos.Bookings.ToList();
        /*    List<Booking> bookings = new List<Booking>();
            bookings.Add(new Booking(){ NumberOfPassengers = 4, ReferenceNumber = 123,DriverName = "Ted"});
            bookings.Add(new Booking() { NumberOfPassengers = 2, ReferenceNumber = 456,DriverName = "Bob"});
            return bookings;*/
        }

       

        public Booking Get(int referenceNumber)
        {
            return repos.Bookings.Single(x => x.BookingId == referenceNumber);
            
        }

        public Booking Create(NewBooking bookingRequest)
        {
            Customer customer = repos.Customers.FirstOrDefault(
                x => x.IMEI == bookingRequest.IMEI && x.PhoneNumber == bookingRequest.PhoneNumber);

            if(customer == null)
            {
                customer = new Customer {IMEI = bookingRequest.IMEI, PhoneNumber = bookingRequest.PhoneNumber};
                repos.Customers.AddObject(customer);
            }
            Booking booking = AutoMapper.Mapper.Map<NewBooking, Booking>(bookingRequest);

            //set a safety default
            if(booking.Latitude == null || booking.Latitude == 0)
            {
                booking.Latitude = (decimal)-35.277752;
                booking.Longitude = (decimal)149.130754;
            }
            booking.CreateDateTime = DateTime.Now.ToUniversalTime();
            booking.Status = "NEW";
            customer.Bookings.Add(booking);
            repos.SaveChanges();
            return booking;
        }

        public Booking Update(Booking booking)
        {
            var original = repos.Bookings.FirstOrDefault(x => x.BookingId == booking.BookingId);
            original.DriverId = booking.DriverId;
            original.PickupSuburb = booking.PickupSuburb;
            
            //repos(booking);
            repos.SaveChanges();
            return booking;
        }
    }
}